package coreservlets;

/** A Runnable as a separate class (variation 1 of 3).
 *  <p>
 *  From <a href="http://courses.coreservlets.com/Course-Materials/">the
 *  coreservlets.com tutorials on JSF 2, PrimeFaces, Ajax, jQuery, GWT, Android,
 *  Spring, Hibernate, JPA, RESTful Web Services, Hadoop, 
 *  servlets, JSP, and Java 7 and Java 8 programming</a>.
 */

// The run method of this separate class can call 
// methods in the main class only because
// (A) A reference to the main class (App1) is passed to the constructor
// (B) The methods in the main class that are called (pause) are public

public class Counter implements Runnable {
  private final App1 mainApp;
  private final int loopLimit;

  public Counter(App1 mainApp, int loopLimit) {
    this.mainApp = mainApp;
    this.loopLimit = loopLimit;
  }

  public void run() {
    for(int i=0; i<loopLimit; i++) {
      String threadName = Thread.currentThread().getName();
      System.out.printf("%s: %s%n", threadName, i);
      mainApp.pause(Math.random()); // Sleep for up to 1 second
    }
  }
}
